package com.hqyj.finance.server.users.financeusers.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.finance.server.users.financeusers.entity.Roles;
import com.hqyj.finance.server.users.financeusers.entity.UsersRoles;
import com.hqyj.finance.server.users.financeusers.mapper.UsersRolesMapper;
import com.hqyj.finance.server.users.financeusers.service.RolesService;
import com.hqyj.finance.server.users.financeusers.service.UsersRolesService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
public class UsersRolesServiceImpl extends ServiceImpl<UsersRolesMapper, UsersRoles> implements UsersRolesService {

    @Resource
    private UsersRolesMapper usersRolesMapper;
    @Resource
    private RolesService rolesService;
    @Override
    public List<Roles> queryUserRolesListByUid(Integer uid) {
        List<UsersRoles> usersRolesList = new ArrayList<UsersRoles>();
        List<Roles> rolesList = new ArrayList<Roles>();
        QueryWrapper<UsersRoles> queryWrapper = new QueryWrapper<UsersRoles>();
        queryWrapper.eq("uid",uid);
        usersRolesList = super.list(queryWrapper);
        if(usersRolesList!=null&&usersRolesList.size()>0){
            for(UsersRoles usersRoles : usersRolesList){
                Roles roles = rolesService.getById(usersRoles.getRid());
                rolesList.add(roles);
            }
        }
        return rolesList;
    }

    @Transactional(rollbackOn = Exception.class)
    @Override
    public boolean updateUserRolesListByUid(Integer uid, List<UsersRoles> usersRoles) throws Exception {
        try{
            //删除该用户所有的用户角色
            usersRolesMapper.removeUsersRolesListByUid(uid);
            if(usersRoles!=null&&usersRoles.size()>0){
                super.saveBatch(usersRoles);
            }

            return true;
        }catch (Exception ex){
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

    }
}
